package com.ktjiaoyu.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ktjiaoyu.crm.config.shiro.MyShiroRealm;
import com.ktjiaoyu.crm.mapper.UserMapper;
import com.ktjiaoyu.crm.pojo.User;
import com.ktjiaoyu.crm.service.UserService;
import com.ktjiaoyu.crm.utils.MD5Util;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    UserMapper userMapper;

    @Override
    public User login(String usrName, String usrPassword) {
        //构造查询条件
        QueryWrapper<User> qw=new QueryWrapper<>();
        qw.eq("usr_name",usrName);
        qw.eq("usr_password",usrPassword);

        return userMapper.selectOne(qw);
    }

    @Override
    public IPage<User> getUsersByPage(Integer pageNo, Integer pageSize, String usrName, Long roleId) {
        //构造分页条件对象
        Page page=new Page(pageNo,pageSize);
        //构造过滤条件对象
        Map<String,Object> param=new HashMap<>();
        param.put("usrName",usrName);
        param.put("roleId",roleId);

        return userMapper.getUsersByPage(page,param);
    }

    @Override
    public int addUser(User user) {
        user.setUsrFlag(1);
        user.setUsrPassword(MD5Util.encryptPassword(user.getUsrPassword()));
        return userMapper.insert(user);
    }

    @Override
    public User getUser(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public int updateUser(User user) {
        user.setUsrPassword(MD5Util.encryptPassword(user.getUsrPassword()));

        //清空所有用户缓存
        RealmSecurityManager realmManager= (RealmSecurityManager) SecurityUtils.getSecurityManager();
        MyShiroRealm realm=(MyShiroRealm)realmManager.getRealms().iterator().next();
        realm.clearAllCacheAuthorizationInfo();

        return userMapper.updateById(user);
    }

    @Override
    public int deleteUser(Long id) {
        return userMapper.deleteById(id);
    }

    @Override
    public User getUserByUsrName(String usrName) {
        return userMapper.getUserByUsrName(usrName);
    }
}
